#!/bin/bash
echo "欢迎使用HMCL MacOS打包脚本"
cd "$(dirname "$0")"
if [ -h "$0" ]; then
	cd "$(dirname "$(readlink "$0")")"
fi
echo "正在获取软件包信息"
src="https://scientificworld.neocities.org/link.txt"
data="$(curl -s "$src")"
sha1="$(echo "$data" | sed -n 1p)"
if [ -f "hmcl.jar" ] && [ "$(sha1sum "hmcl.jar" 2>&1 | cut -d ' ' -f 1)" = "$sha1" ]; then
	echo "软件包已经存在，直接进入打包阶段"
else
	link="$(echo "$data" | sed -n 3p)"
	echo "正在下载软件包，请稍候"
	curl -C - -o hmcl.jar --progress-bar "$link"
	if [ "$?" != "0" ]; then
		echo "下载出现错误，请重试"
		exit
	fi
fi
echo "正在检测图标"
if [ -f "icon.icns" ]; then
	echo "图标已经存在，使用当前图标"
else
	echo "正在生成图标"
	rm -rf icon.iconset 2>&1 >/dev/null
	if [ ! -f "icon.jpeg" ]; then
		curl -o icon.jpeg "$(echo "$data" | sed -n 4p)"
	fi
	mkdir -p "icon.iconset"
	for size in 16 32 128 256 512; do
		sips -s format png -z "$size" "$size" "icon.jpeg" --out "icon.iconset/icon_${size}x${size}.png"
		size=$[$size*2]
		sips -s format png -z "$size" "$size" "icon.jpeg" --out "icon.iconset/icon_$[$size/2]x$[$size/2]@2x.png"
	done
	iconutil -c icns "icon.iconset" -o "icon.icns"
	if [ "$?" != "0" ]; then
		echo "图标生成失败"
		rm -rf icon.jpeg icon.iconset 2>&1 >/dev/null
		exit
	fi
	rm -rf icon.iconset 2>&1 >/dev/null
fi
echo "正在生成应用"
if [ -e "hmcl.app" ]; then
	rm -rf hmcl.app
fi
mkdir -p hmcl.app/Contents
cd hmcl.app/Contents
mkdir MacOS Resources
cat > Info.plist <<- eof
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDisplayName</key>
<string>hmcl</string>
<key>CFBundleExecutable</key>
<string>hmcl</string>
<key>CFBundleIconFile</key>
<string>icon.icns</string>
<key>CFBundleIdentifier</key>
<string>com.huangyuhui.hmcl</string>
<key>CFBundleName</key>
<string>hmcl</string>
<key>CFBundleShortVersionString</key>
<string>$(echo "$data" | sed -n 2p)</string>
<key>CFBundleVersion</key>
<string>$(echo "$data" | sed -n 2p)</string>
</dict>
</plist>
eof
cat > MacOS/hmcl <<- eof
#!/bin/bash
cd "\$(dirname "\$0")"
if [ -h "\$0" ]; then
	cd "\$(dirname "\$(readlink "\$0")")"
fi
java -jar hmcl.jar
eof
chmod +x MacOS/hmcl
mv ../../icon.icns Resources
cp ../../hmcl.jar MacOS
cd ../..
echo "生成完成，位置：$(pwd)/hmcl.app"
